<?php

/**

 * 后台基类
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn>
 */

namespace Home\Controller;

use Think\Controller;

class BaseController extends Controller {

    public $limit = 10;
    public $model;

    public function _initialize() {
        if (!session('user_id')) {
            $this->redirect('Login/login');
        }

//        $attendDate = date('Y') - 1 . '-' . date('m-d 00:00:00');
//        $attendMap['stime'] = array('lt', $attendDate);
//        M('inoutdata')->where($attendMap)->delete();

        $this->userMenus = session('userMenus');

        //当前用户信息
        $this->userinfo = M('user')->where('user_id="' . session('user_id') . '"')->find();

        //当天外出人员信息
        unset($map);
        $map['submit_time'] = array('like', '%' . date('Y-m-d') . '%');
        $this->outCount = count($this->getAbsenceUser('attend_out', $map));
        $this->outList = $this->getAbsenceUser('attend_out', $map);

        //当天出差人员信息
        unset($map);
        $map['_string'] = ' evection_date1 <= "' . date('Y-m-d 23:59:59') . '" and evection_date2 >= "' . date('Y-m-d H:i:s') . '"';
        $this->evectionCount = count($this->getAbsenceUser('attend_evection', $map));
        $this->evectionList = $this->getAbsenceUser('attend_evection', $map);

        //当天请假人员
        unset($map);
        $map['_string'] = ' leave_date1 <= "' . date('Y-m-d H:i:s') . '" and leave_date2 >= "' . date('Y-m-d H:i:s') . '"';
        $this->leaveCount = count($this->getAbsenceUser('attend_leave', $map));
        $this->leaveList = $this->getAbsenceUser('attend_leave', $map);

        $this->attendCount = $this->outCount + $this->evectionCount + $this->leaveCount;

        $this->web = M('web')->find(1);

        $this->user = session('user_id');

        $url = $_SERVER['PHP_SELF'];
    }

    protected function _empty() {
        //空方法时跳转
        $this->redirect('Bese/error');
    }

    //获取当天外出人员
    private function getAbsenceUser($table, $map) {
        $data = M($table)->where($map)->select();
        if (!empty($data)) {
            foreach ($data as $key => $row) {
                //获取头像
                $data[$key]['head'] = M('user')->where('user_id="' . $row['user_id'] . '"')->getField('head');
            }
        } else {
            $data = [];
        }

        return $data;
    }

    //回车搜索人员
    public function searchUser() {
        $user = I('name');
        $user_id = M('user')->where('user_name="' . $user . '"')->getField('user_id');
        if (!$user_id) {
            $this->ajaxReturn([$data[0] => '没有此用户']);
        }
        $map['user_id'] = $user_id;
        $map['submit_time'] = array('like', '%' . date('Y-m-d') . '%');
        $data = $this->getAbsenceUser('attend_out', $map);
        if ($data) {
            $data[0]['attendType'] = '外出人员';
            $data[0]['username'] = getChineseName($data[0]['user_id']);
            $data[0]['head'] = M('user')->where('user_id="' . $data[0]['user_id'] . '"')->getField('head');
            $this->ajaxReturn($data[0]);
        }

        unset($map['submit_time']);
        $map['_string'] = ' evection_date1 <= "' . date('Y-m-d') . '" and evection_date2 >= "' . date('Y-m-d') . '"';
        $data = $this->getAbsenceUser('attend_evection', $map);
        if ($data) {
            $data[0]['attendType'] = '出差人员';
            $data[0]['username'] = getChineseName($data[0]['user_id']);
            $data[0]['head'] = M('user')->where('user_id="' . $data[0]['user_id'] . '"')->getField('head');
            $this->ajaxReturn($data[0]);
        }

        $map['_string'] = ' leave_date1 <= "' . date('Y-m-d') . '" and leave_date2 >= "' . date('Y-m-d') . '"';
        $data = $this->getAbsenceUser('attend_leave', $map);
        if ($data) {
            $data[0]['attendType'] = '请假人员';
            $data[0]['username'] = getChineseName($data[0]['user_id']);
            $data[0]['head'] = M('user')->where('user_id="' . $data[0]['user_id'] . '"')->getField('head');
            $this->ajaxReturn($data[0]);
        }
    }

    //分页
    protected function pageLists($count, $limit = 9) {
        $Page = new \Think\Page($count, $limit);
        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');
        $Page->setConfig('first', '首页');
        $Page->setConfig('last', '尾页');
        $Page->rollPage = 5;

        return $Page->show();
    }

    //文件上传
    protected function upfile($url) {
        $file = $_POST['imgfile'];
        $filename = end(explode('\\', $file));

        $config = array(
            'maxSize' => 20971520,
            'rootPath' => $url,
            'exts' => array('txt', 'pdf', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx', 'zip', 'rar', 'png', 'jpg', 'jpeg', 'psd', 'bmp', 'gif', 'tiff', 'zip', 'html'),
            'savePath' => '', //保存路径
            'subName' => '',
        );
        $upload = new \Think\Upload($config); // 实例化上传类
        // 上传文件 

        $info = $upload->uploadOne($_FILES['imgfile']);
        $url = $filename . ';' . substr($url, 1) . $info['savepath'] . $info['savename'];
        if (!$info) {
            $this->ajaxReturn("false", "EVAL");
        } else {
            $this->ajaxReturn($url, "EVAL");
        }
    }

    public function delFile() {
        $url = I('url');
        if ($url) {
            $res = @unlink('.' . $url);
        }
        if (I('table')) {
            $table = I('table');
            $map[$field] = I('id');
            $data['uploads'] = '';
            $data['uploads_url'] = '';

            $res = M($table)->where($map)->save($data);
        }

        $return['status'] = $res !== false ? 1 : 0;
        $this->ajaxReturn($return);
    }

    //弹窗
    public function layer() {
        $type = I('type');
        $user_id = session('user_id');
        $dia_id = I('dia_id');
        $comment_id = I('comment_id');
        $news_id = I('news_id');
        switch ($type) {
            case 1:
                //获取用户
                $departs = M('department')->order('dept_no')->select();
                $this->departs = $departs;

                $this->flow_id = I('flow_id') != 'undefined' ? I('flow_id') : '';
                $this->run_id = I('run_id');
                $this->prcs_id = I('prcs_id');
                $this->auto_type = I('auto_type');
                $this->id = I('id');    //流程外其他选择人员
                $this->table_key = I('key');  //工作计划模块用来区分不同选择人员的key
                $this->flow_type = I('flow_type');  //设计流程自动选人规则中的选择人员
                $this->form = I('form');    //流程表单中增加选择人员控件
                $users = $this->getData(I('flow_id'), I('prcs_id'), I('run_id'), I('auto_type'), '', 8);

                //添加步驟名和是否会签标记到$data數組中
                $users = addPrcsname($users, I('flow_id'), I('prcs_id'));
                $count = $users[0]['count'];
                $this->pages = $this->pageLists($count);
//print_r($users);
                $this->users = $users;
                $this->one = I('one') ? 1 : 0;
                break;
            case 2:
                $flow_prcs = I('prcs_id');  //流程步骤
                $run_id = I('run_id');
                //添加回退意见
                if (isset($_GET['feedback']) && I('feedback')) {
                    $fdata['content'] = I('feedback');
                    $fdata['run_id'] = $run_id;
                    $fdata['prcs_id'] = I('prcsNum');
                    $fdata['flow_prcs'] = I('currPrcs');
                    $fdata['user_id'] = session('user_id');
                    $fdata['edit_time'] = date('Y-m-d H:i:s');

                    $fmap['run_id'] = $run_id;
                    $fmap['prcs_id'] = I('prcsNum');
                    $fmap['flow_prcs'] = I('currPrcs');
                    $fmap['user_id'] = session('user_id');
                    $one = M('flow_run_feedback')->where($fmap)->count();
                    if (!$one) {
                        M('flow_run_feedback')->add($fdata);
                    }
                }

                $flow_id = I('flow_id');
                $map['run_id'] = $run_id;
                $map['flow_prcs'] = array('lt', $flow_prcs);
                $prcs_ids = M('flow_run_prcs')->where($map)->getField('flow_prcs', true);
//                print_r($prcs_ids);
                if (!is_array($prcs_ids)) {
                    $prcs_ids[] = $prcs_ids;
                }

                unset($map['run_id']);
                $map['flow_id'] = $flow_id;
                $map['prcs_id'] = array('lt', $flow_prcs);
                $runs = M('flow_process')->field('flow_id,prcs_id,prcs_name')->where($map)->order('prcs_id')->select();
                foreach ($runs as $key => $row) {
                    $runs[$key]['run_id'] = $run_id;
                }
//                print_r($runs);
                $this->runs = $runs;
                $this->currFlowPrcs = I('prcs_id');
                $this->currPrcsId = I('currPrcs');
                break;
            case 3:
                //获取部门
                $this->depts = M('department')->order('dept_id')->select();
                $this->field = I('field');
                break;
            case 4:
                //获取回复日志的id
                $this->dia_id = $dia_id;
                $this->comment_id = $comment_id;
                break;
            case 5: //计划批注
                $this->id = I('id');
                $this->is_end = I('is_end');
                break;
            case 6:
                //获取回复日志的id
                $this->dia_id = I('dia_id');
                $this->comment_id = I('comment_id');
                break;
            case 7:
                //获取角色
                $this->privs = M('user_priv')->order('priv_no')->select();
                $this->field = I('field');
                $this->key_id = I('key');
                break;
            case 8:
                //获取公告或者公文信息
                $this->table = I('table');
                if (I('table') == 'document') {
                    $data = M('document')->where('document_id=' . I('id'))->find();
                } elseif (I('table') == 'notify') {
                    $data = M('notify')->where('notify_id=' . I('id'))->find();
                    $data['begin_date'] = $data['begin_date'] ? date("Y-m-d", $data['begin_date']) : '';
                    $data['end_date'] = $data['end_date'] ? date("Y-m-d", $data['end_date']) : '';
                }
                $this->data = $data;
                break;
            case 9:
                //获取公告、公文
                $this->table = I('table');
                if (I('table') == 'document') {
                    $this->data = M('document')->where('document_id = ' . I('id'))->find();
                } elseif (I('table') == 'notify') {
                    $this->data = M('notify')->where('notify_id = ' . I('id'))->find();
                }
                break;
            case 10:
                //取当月前12个月
                for ($i = 1; $i <= 12; $i++) {
                    if (count($arr) != 12) {
                        $month[date('Y-m', strtotime("-" . $i . " month"))] = date('Y年m', strtotime("-" . $i . " month")) . '月';
                    }
                }
                $this->months = $month;
                break;
            case 11:
                //流程说明
                $flow_id = I('flow_id');
                $this->info = M('flow_type')->where('flow_id=' . $flow_id)->find();
                break;
            case 12:
                //获取回复新闻评论的id
                $this->news_id = $news_id;
                $this->comment_id = $comment_id;
                break;
            case 13:
                //设计流程 -> 新建管理权限
                $this->flow_id = I('flow_id');
                //修改管理权限 flow_priv=>id
                $this->id = I('id');
                //获取当前权限
                $priv = M('flow_priv')->find(I('id'));
                $priv['users'] = $priv['user'] ? explode(',', rtrim($priv['user'], ',')) : '';
                $priv['depts'] = $priv['dept'] ? explode(',', rtrim($priv['dept'], ',')) : '';
                $priv['roles'] = $priv['role'] ? explode(',', rtrim($priv['role'], ',')) : '';

                $this->priv = $priv;
                break;
            case 14:
                $form_id = I('form_id');
                $one = M('flow_form_type')->where('FORM_ID = ' . $form_id)->find();
                if (substr(trim($one['print_model']), 0, 1) == '?')
                    $content = substr(trim($one['print_model']), 1, -1);  //必须用$_post，否则无法转换
                else
                    $content = trim($one['print_model']);
                import('Org.Formdesign');
                $formdesign = new \Formdesign;
                $parse_content = $formdesign->parse_form($content, $one['fields']);


                $design_content = $formdesign->unparse_form(array(
                    'content_parse' => $parse_content['parse'],
                    'content_data' => serialize($parse_content['data']), //保存后是 serialize，所以这里也一样
                        ), array(), array('action' => 'preview'));
                $this->design_content = $design_content;
                break;
            case 15:
                $dia_id = I('dia_id');
                if ($dia_id) {
                    $diary = M('diary')->where('dia_id = ' . $dia_id)->find();
                    $this->diary = $diary;
                }
                $cur_date = I('date');
                $weeknames = array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
                $dateArr = explode("-", $cur_date);

                $week = date("w", mktime(0, 0, 0, $dateArr[1], $dateArr[2], $dateArr[0]));
                $weekname = $weeknames[$week];
                $subject = $cur_date . " " . $weekname . " 日志";
                $this->subject = $subject;
                $this->dia_id = $dia_id;
                $this->date = I('date');
                break;
            case 16:
                //新增类别
                if (I('ctrl') == 'goods') {
                    $this->cates = M('goods_type')->select();
                } elseif (I('ctrl') == 'plan') {
                    $map['pid'] = 0;
                    $cates = M('plan_type')->where($map)->order('type_no')->select();
                    foreach ($cates as $key => $row) {
                        $cates[$key]['id'] = $row['type_id'];
                        $cates[$key]['name'] = $row['type_name'];
                    }
                    $this->cates = $cates;
                } else {
                    $map['parent_no'] = I('ctrl');
                    $cates = M('sys_code')->where($map)->order('code_no')->select();
                    foreach ($cates as $key => $row) {
                        $cates[$key]['id'] = $row['code_id'];
                        $cates[$key]['name'] = $row['code_name'];
                    }
                    $this->cates = $cates;
                }
                $this->ctrl = I('ctrl');
                break;
            case 17:
                //我的分组
                $this->groups = M('address_group')->where('user_id="' . session('user_id') . '"')->select();
                break;
            case 18:
                //获取部门
                $this->depts = M('department')->order('dept_no')->select();
                $table = I('ctrl') == 'flow' ? 'flow_sort' : 'form_sort';
                $this->info = M($table)->find(I('id'));
                $this->ctrl = I('ctrl');
                break;
            case 19:
                if (I('id')) {
                    $this->questionId = I('id');
                }
                break;
            case 20:
                //获取问题与建议列表
                if (in_array(session('user_id'), ['qiaoshoujuan', 'zhangyingheng', 'zhoulingling', '1213'])) {
                    $is_handle = 1;
                } else {
                    $is_handle = 0;
                }
                if ($is_handle == 1) {
                    $list = M('advice')->where('parent_id = 0')->order('id desc')->select();
                } else {
                    $list = M('advice')->where('user_id like "%' . session('user_id') . '%" and parent_id = 0')->order('id desc')->select();
                }
                foreach ($list as $k => $v) {
                    $list[$k]['create_time'] = date("Y-m-d H:i:s", $v['create_time']);
                    if ($v['uploads_url']) {
                        $uploads_url = explode(';', $v['uploads_url']);
                        $list[$k]['uploads_url'] = $uploads_url;
                    }
                    $reply = M('advice')->where('parent_id = ' . $v['id'])->select();
                    if ($reply) {
                        foreach ($reply as $key => $value) {
                            $reply[$key]['create_time'] = $value['create_time'] ? date("Y-m-d H:i:s", $value['create_time']) : '';
                        }
                        $list[$k]['reply'] = $reply;
                    }
                }
//                echo '<pre>',print_r($list);die;
                $this->is_handle = $is_handle;
                $this->list = $list;
        }

        $this->type = $type;
        $this->display('Base/layer');
    }

    //ajax分页显示用户姓名
    public function getAjaxPage() {
        $run_id = I('run_id');
        $prcs_id = I('prcs_id');
        $auto_type = I('auto_type');

        $dept_id = I('dept_id') ? I('dept_id') : '';
        if (strpos($dept_id, '.html')) {
            $end = strpos($dept_id, '.');
            $dept_id = substr($dept_id, 0, $end);
        }

        $flow_id = I('flow_id') ? I('flow_id') : 0;
        $p = I('get.p');
        $limit = 8;
        $list = $this->getData($flow_id, $prcs_id, $run_id, $auto_type, $dept_id, $limit);

        //添加步驟名和是否会签标记到$data數組中
        $list = addPrcsname($list, $flow_id, $prcs_id);
        foreach ($list as $key => $row) {
            $list[$key]['flow_id'] = $flow_id;
        }

        $page = new \Think\MyPage($list[0]['count'], $limit);
        $data['list'] = $list;
        $data['first'] = $page->first();
        $data['prev'] = $page->prev();
        $data['next'] = $page->next();
        $data['last'] = $page->last();
        $data['curr'] = $p;
        $data['page'] = explode(' ', $page->pageList_ajax());

        $this->ajaxReturn($data);
    }

    /*
     * 通过流程步骤设置的条件，取出对应的用户
     * param $flow_id   流程id
     * param $prcs_id   步骤id
     * param $run_id    发起流程id
     * param $auto_type 自动选人规则 0：不自动选择
     * param $dept_id   部门id
     * return array
     */

    protected function getData($flow_id = '', $prcs_id = '', $run_id = '', $auto_type = '', $dept_id = '', $limit = '') {
        $limit = $limit ? $limit : $this->limit;
        $p = I('get.p', 1, 'intval');
        $start = $limit * ($p - 1);
        if (!$auto_type && $dept_id) {
            $sql = "select user_id,user_name,dept_id,user.user_priv,priv_name,priv_no from user left join user_priv on user.user_priv = user_priv.user_priv where dept_id = " . $dept_id . " order by priv_no limit " . $start . "," . $limit;
            $data = M()->query($sql);

            //获取总条数
            $sql1 = "select count(*) from user left join user_priv on user.user_priv = user_priv.user_priv where dept_id= " . $dept_id;
            $count = M()->query($sql1);
            foreach ($data as $key => $row) {
                $data[$key]['checked'] = 0;
                $data[$key]['count'] = $count[0]['count(*)'];
            }
        } else {
            if ($auto_type == 1) {
                $map['run_id'] = $run_id;
                $map['prcs_id'] = 1;
                $sql['user_id'] = M('flow_run_prcs')->where($map)->getField('user_id');
            } else {
                if ($flow_id) {
                    $map['flow_id'] = $flow_id;
                    $map['prcs_id'] = $prcs_id;
                    $step = M('flow_process')->field('prcs_id,prcs_name,prcs_dept,prcs_priv,prcs_user,prcs_to,feedback,prcs_in,prcs_in_set,allow_back,top_default')->where($map)->find();
//                    var_dump($step);
                    $sql = '';

                    //如果$dept_id存在，为指定部门（选人页面，点击部门时用）
                    if ($dept_id) {
                        $sql .= "dept_id = " . $dept_id;
                    }

                    //$dept_id不存在，通过当前步骤获取部门（下一步页面获取符合条件的用户时用）
                    $is_str = strstr($step['prcs_name'], '部门');
                    if (($step['prcs_dept'] == '') && $is_str !== false) {
                        //如果当前步骤名包含部门并且步骤中部门为空，则获取第一步经办人的部门
                        unset($map['prcs_id']);
                        $map['run_id'] = $run_id;
                        $uMap['user_id'] = M('flow_run')->where($map)->getField('begin_user');
                        $user = M('user')->field('user_id,user_name,user_priv,user_priv_other,dept_id,dept_id_other')->where($uMap)->find();
                        $step['prcs_dept'] = $user['dept_id'] . ',' . $user['dept_id_other'];

                        // echo $step['prcs_dept'];
                        if ($step['prcs_dept']) {
                            $depts = explode(',', rtrim($step['prcs_dept'], ','));
                        }
                        if ($sql !== '') {
                            $sql .= " and (dept_id in (" . rtrim($step['prcs_dept'], ',') . ")";
                        } else {
                            $sql .= "(dept_id in (" . rtrim($step['prcs_dept'], ',') . ")";
                        }

                        //获取副部门的条件
                        if ($depts) {
                            foreach ($depts as $key => $row) {
                                if ($row) {
                                    $sql .= " or dept_id_other like '%" . $row . "%'";
                                }
                            }
                        }
                        $sql .= ")";
                    } else if ($step['prcs_dept'] == 'ALL_DEPT') {
                        $dept_ids = M('department')->getField('dept_id', true);
                        $dept_ids = implode(',', $dept_ids);
                        if ($sql !== '') {
                            $sql .= ' and dept_id in (' . $dept_ids . ')';
                        } else {
                            $sql .= 'dept_id in (' . $dept_ids . ')';
                        }
                    }

                    if ($step['prcs_priv']) {
                        $privs = explode(',', $step['prcs_priv']);
                        //$map['USER_PRIV'] = array('in', $privs);     //角色条件
                        if ($step['prcs_priv']) {
                            if ($sql != '') {
                                $sql .= " and (user_priv in (" . rtrim($step['prcs_priv'], ',') . ")";
                            } else {
                                $sql .= "(user_priv in (" . rtrim($step['prcs_priv'], ',') . ")";
                            }
                        }

                        if ($privs) {
                            foreach ($privs as $key => $row) {
                                if ($row) {
                                    $sql .= " or user_priv_other like '%" . $row . "%'";
                                }
                            }
                        }
                        $sql .= ")";
                    }

                    $users = explode(',', $step['prcs_user']);
                    foreach ($users as $k => $u) {
                        if ($u) {
                            $users[$k] = '"' . $u . '"';
                        }
                    }
                    $users = implode(',', $users);
                    if ($step['prcs_user']) {
                        if ($sql != '') {
                            $sql .= " and user_id in (" . rtrim($users, ',') . ")";
                        } else {
                            $sql .= "user_id in (" . rtrim($users, ',') . ")";
                        }
                    }

                    //公文发送：最后一步显示发起人的姓名
                    if ($flow_id == 93 && $prcs_id == 8) {
                        $res_1 = M('flow_run')->field('begin_user')->where(" run_id = $run_id and flow_id = 93")->find();
                        $sql = " user_id = '" . $res_1['begin_user'] . "'";
                    }
                    //内部请示：最后一步显示发起人的姓名
                    if ($flow_id == 165 && $prcs_id == 6) {
                        $res_1 = M('flow_run')->field('begin_user')->where(" run_id = $run_id and flow_id = 165")->find();
                        $sql = " user_id = '" . $res_1['begin_user'] . "'";
                    }
                } else {
                    //非流程类选择人员
                    $sql = ' dept_id != 0';
                }
            }

            $data = M('user')->field('user_id,user_name,user_priv,user_priv_other,dept_id,dept_id_other')->where($sql)->limit($start, $limit)->select();
            //获取总条数
            $count = M('user')->where($sql)->count();

            foreach ($data as $k => $r) {
                $data[$k]['count'] = $count;
                if ($sql && $auto_type != 0 && $count == 1) {
                    $data[$k]['checked'] = 1;
                } else {
                    $data[$k]['checked'] = 0;
                }
            }
        }
        //$data[] = M('user')->field('user_id,USER_NAME,USER_PRIV,USER_PRIV_OTHER,DEPT_ID,DEPT_ID_OTHER')->where('user_id="zhangyingheng"')->find();
        return $data;
    }

    public function delete() {
        $id = array_unique((array) I('id', 0));
        $map = array('id' => array('in', $id));
        $res = M(I('table'))->where($map)->delete();
        if ($res !== FALSE) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //按类型获取个人计划百分比
    protected function userProcessDetail($planTypes) {
        //取周一和周日
        $week = getWeekDate();
        //本人
        foreach ($planTypes as $key => $row) {
            if (getPlanMode($row['type_id']) == 0) {
                $where['executor'] = array('like', '%' . session('user_id') . '%');
            } else {
                $where['manager'] = session('user_id');
                $where['participator'] = array('like', '%' . session('user_id') . '%');
            }

            $map['type'] = $row['type_id'];
            $map['sms_flag'] = 0;
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
            $plans[$row['type_id']] = M('work_plan')->where($map)->order('begin_date desc')->select();
            $plans[$row['type_id']]['name'] = $row['type_name'];
        }

        $step = 1;
        foreach ($plans as $key => $row) {
            $total = $this->getPercent($row);
            $num = (count($row) - 1) ? count($row) - 1 : 0;
            if ($row[0]) {
                $count = (round(($total / ($num * 100)), 2) * 100) . '%';
            } else {
                $count = '0%';
            }
            $percent[$key]['name'] = $row['name'];
            $percent[$key]['count'] = $num;
            $percent[$key]['total'] = $count;
            $percent[$key]['step'] = $step++;
        }
        return $percent;
    }

    /*
     * 2018-3-14  公司领导需要看到各部门总计划完成百分比
     */

    protected function leaderProcessDetail($planTypes) {
        //获取所有部门
        $depts = M('department')->where('dept_name != "公司领导"')->getField('dept_id', true);
        foreach ($depts as $key => $row) {
            $data = [];
            $users = M('user')->where('dept_id=' . $row)->getField('user_id', true);
            if (!is_array($users)) {
                $users[] = $users;
            }

            $map['sms_flag'] = 0;
            foreach ($users as $u_key => $u_row) {
                $where['executor'] = array('like', '%' . $u_row . '%');
                $where['manager'] = array('like', '%' . $u_row . '%');
                $where['participator'] = array('like', '%' . $u_row . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $data[$row][] = M('work_plan')->where($map)->order('begin_date desc')->select();
            }
            $datas[$row] = $this->array2D($data[$row]);
        }
//        print_r($datas);
        $percent = $this->getPlanTypePercent($datas);
//        print_r($percent);
        return $percent;
    }

    protected function getPercent($data) {
        $finish = 0;
        foreach ($data as $key => $row) {
//            $map['PLAN_ID'] = $row['plan_id'];
//            $finish += M('work_detail')->where($map)->max('PERCENT');
            $finish += $row['total_percent'];   //只取每条的总进度
        }
        return $finish;
    }

    //二维数组去重
    public function array2D($tempPlan) {
        foreach ($tempPlan as $a => $b) {
            foreach ($b as $x => $y) {
                $plan[] = $y;
            }
        }
        $result = array();
        foreach ($plan as $key => $value) {
            $has = false;
            foreach ($result as $val) {
                if ($val['plan_id'] == $value['plan_id']) {
                    $has = true;
                    break;
                }
            }
            if (!$has)
                $result[] = $value;
        }
        foreach ($result as $key => $row) {
            $result[$key]['today'] = date('Y-m-d');
        }
        return $this->bubble($result);
    }

    //冒泡排序
    private function bubble($data) {
        $len = count($data);
        for ($i = 0; $i <= $len; $i++) {
            for ($j = 0; $j < $len - 1; $j++) {
                if ($data[$j]['begin_date'] < $data[$j + 1]['begin_date']) {
                    $tmp = $data[$j + 1];
                    $data[$j + 1] = $data[$j];
                    $data[$j] = $tmp;
                }
            }
        }
        return $data;
    }

    //按分类计划总条数获取百分比
    private function getPlanTypePercent($datas) {
        $step = 1;
        foreach ($datas as $key => $row) {
            if ($step > 4) {
                $step = 1;
            }
            $total = $this->getPercent($row);
            $num = count($row) ? count($row) : 0;
            if ($row[0]) {
                $count = (round(($total / ($num * 100)), 2) * 100) . '%';
            } else {
                $count = '0%';
            }
            $percent[$key]['deptName'] = getDeptName($key);
            $percent[$key]['type'] = M('plan_type')->where('type_id=' . $key)->getField('type_name');
            $percent[$key]['count'] = $num;
            $percent[$key]['total'] = $count;
            $percent[$key]['step'] = $step++;
        }
        return $percent;
    }

    //获取本部门计划分类进展
    protected function getDeptPercent() {
        //获取公司领导部门id
        $leaderDeptId = M('department')->where('dept_name="公司领导"')->getField('dept_id');
        $dept_id = session('dept_id') == $leaderDeptId ? session('dept_id_other') : session('dept_id');
        //获取本部门所有员工
        $deptUsers = M('user')->where('dept_id=' . $dept_id)->getField('user_id', true);
        if (!is_array($deptUsers)) {
            $deptUsers[] = $deptUsers;
        }

        $counts = M('plan_type')->where('pid = 0')->order('type_no')->select();
        foreach ($counts as $key => $row) {
            $map['type'] = $row['type_id'];
            $map['sms_flag'] = 0;
            $data = array();
            foreach ($deptUsers as $u_key => $value) {
                $where['executor'] = array('like', '%' . $value . '%');
                $where['manager'] = array('like', '%' . $value . '%');
                $where['participator'] = array('like', '%' . $value . '%');
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $data[] = M('work_plan')->where($map)->order('begin_date desc')->select();
            }
            $plans[$row['type_id']] = $this->array2D($data);
        }
        $deptPercent = $this->getPlanTypePercent($plans);
        return $deptPercent;
    }

    /*
     * 获取流程列表
     * params   $flag  1:未办结  2已办结  3查询
     * params   $limit  条数    0所有
     * params   $type   1:flow_flag:1,2（未办结）  2:flow_flag:3,4（已办结）  空：流程查询（执行中:flow_run=>end_time is null; 执行结束：flow_run=>end_time not null）
     * params   $where  条件
     * return array
     */

    protected function getLists($flag, $limit, $type = "", $where = "") {
        $p = I('get.p', 1, 'intval');
//        $start = $limit * ($p - 1);

        if ($flag != 3) {
            $map['user_id'] = session('user_id');

            //取所有和我相关的run_id
            $myRun = M('flow_run_prcs')->field('run_id,user_id,prcs_id,prcs_flag')->where($map)->order('run_id desc,create_time asc')->select();
            foreach ($myRun as $key => $row) {
                $runIds[$row['run_id']] = $row;
            }
            if ($flag !== '') {
                //分已办结和未办结状态
                foreach ($runIds as $key => $row) {
                    if ($flag == 1 && ($row['prcs_flag'] == 1 || $row['prcs_flag'] == 2)) {
                        $ids[] = $key;
                    }
                    if ($flag == 2 && ($row['prcs_flag'] == 3 || $row['prcs_flag'] == 4)) {
                        $ids[] = $key;
                    }
                }
            } else {
                //不区分状态
                foreach ($runIds as $key => $row) {
                    $ids[] = $key;
                }
            }
            if (!empty($ids)) {
                $rMap['run_id'] = array('in', $ids);
//                $rMap['DEL_FLAG'] = 0;
            } else {
                return;
            }
        }

        if ($where) {
            $rMap['_complex'] = $where;
        }
        $rMap['del_flag'] = 0;

        //只查询一年之内的数据
        $currYear = date('Y') - 1 . '-' . date('m-d 00:00:00');
        $rMap['begin_time'] = array('gt', $currYear);

//        print_r($rMap);
        if ($limit != 0) {
            $runs = M('flow_run')->field('run_id,run_name,flow_id,BEGIN_USER,DEL_FLAG')->where($rMap)->page($p, $limit)->order('begin_time desc')->select();
        } else {
            $runs = M('flow_run')->field('run_id,run_name,flow_id,BEGIN_USER,DEL_FLAG')->where($rMap)->order('begin_time desc')->select();
        }

        if (!empty($runs)) {
            foreach ($runs as $key => $row) {
                //获取表单信息（名称，from_id,排序）
                $tMap['run_id'] = $row['run_id'];
                $flow_id = $row['flow_id'];
                $runs[$key]['flow_type'] = M('flow_type')->field('flow_name,form_id,flow_sort')->where('flow_id=' . $flow_id)->find();

                //取创建时间
                $runs[$key]['create_time'] = M('flow_run_prcs')->where(array('run_id' => $row['run_id'], 'user_id' => session('user_id')))->getField('create_time');

                //获取当前流程总进度
                $maxMap['flow_id'] = $flow_id;
                $runs[$key]['maxPrcs'] = M('flow_process')->where($maxMap)->max('prcs_id');

                //获取当前处理人 flow_run_prcs prcs_flag=3(已转交) or prcs_flag=4(已办结)
                $uMap['run_id'] = $row['run_id'];
                if ($type == 1) {
                    $uMap['prcs_flag'] = array('in', [1, 2]);
                } elseif ($type == 2) {
                    $uMap['prcs_flag'] = array('in', [3, 4]);
                }
                $tmp = M('flow_run_prcs')->where($uMap)->order('prcs_id DESC,create_time DESC')->limit(1)->find();
                $runs[$key]['flow_run_prcs'] = $tmp;

                //判断流程当前最后一步是否为会签，如果全部为4：已办结，否则：未办结  by zyh 2018/7/23
                $fMap['prcs_id'] = $tmp['flow_prcs'];
                $fMap['flow_id'] = $flow_id;
                $flowName = M('flow_process')->where($fMap)->getField('prcs_name');
                if (strpos($flowName, '会签') !== false) {
                    $currMap['FLOW_PRCS'] = $tmp['flow_prcs'];
                    $currMap['run_id'] = $row['run_id'];
                    $currMap['prcs_flag'] = array('in', [1, 2]);
                    $unfinish = M('flow_run_prcs')->where($currMap)->count();
                    //流程当前状态
                    $runs[$key]['flowCurrStatus'] = $unfinish ? 1 : 4;
                } else {
                    //流程当前状态
                    $runs[$key]['flowCurrStatus'] = $tmp['prcs_flag'];
                }

                //获取本人prcs状态
                $sMap['run_id'] = $row['run_id'];
                $sMap['user_id'] = session('user_id');
                $self = M('flow_run_prcs')->where($sMap)->order('prcs_id DESC,create_time DESC')->limit(1)->find();

                $runs[$key]['currStatus'] = $self['prcs_flag']; //本人当前状态
                $runs[$key]['currPrcs'] = $tmp['flow_prcs'];   //当前步骤
                //获取当前处理步骤
                $runs[$key]['prcs_name'] = getStepName($flow_id, $runs[$key]['currPrcs']);

                //获取提醒时间
                $runs[$key]['remind'] = $tmp['remind_time'];

                //判断该条流程当前用户是否有管理权限
                $flowIds = getUserFlowPriv(0);
//                print_r($flowIds);
                if (!hasFlowPriv($flowIds, $row['flow_id'])) {
                    $runs[$key]['flowpriv'] = 0;
                } else {
                    $runs[$key]['flowpriv'] = 1;
                }
            }
        } else {
            $runs = [];
        }
//        print_r($runs);
        return $runs;
    }

    //新增类别
    public function saveCate() {
        if (I('addname')) {
            if (I('ctrl') == 'goods') {
                //新增
                $data['name'] = trim(I('addname'));
                $row = M('goods_type')->where('name="' . trim(I('addname')) . '"')->count();
                if (!$row) {
                    $res = M('goods_type')->add($data);
                } else {
                    $return = ['info' => '类别已存在', 'status' => 0, 'icon' => 5];
                }
            } elseif (I('ctrl') == 'plan') {
                //新增
                $data['type_name'] = trim(I('addname'));
                $data['mode'] = I('mode');
                $data['user_id'] = session('user_id');
                $data['pid'] = 0;
                $data['type_no'] = 10;  //默认排序
                $row = M('plan_type')->where('type_name="' . trim(I('addname')) . '"')->count();
                if (!$row) {
                    $res = M('plan_type')->add($data);
                } else {
                    $return = ['info' => '类别已存在', 'status' => 0, 'icon' => 5];
                }
            } else {
                //新增
                $data['code_name'] = trim(I('addname'));
                $data['parent_no'] = I('ctrl');

                $row = M('sys_code')->where('code_name="' . trim(I('addname')) . '" and parent_no = "' . I('ctrl') . '"')->count();
                if (!$row) {
                    $count = M('sys_code')->where('parent_no = "' . I('ctrl') . '"')->count();
                    $data['code_no'] = $count + 1;
                    $data = array_change_key_case($data, CASE_UPPER);
                    $res = M('sys_code')->add($data);
                } else {
                    $return = ['info' => '类别已存在', 'status' => 0, 'icon' => 5];
                }
            }
        } else {
            //编辑
            $data = I('post.');
            if ($data['id'][0]) {
                if (I('ctrl') == 'goods') {
                    for ($i = 0; $i < count($data['id']); $i++) {
                        $sdata['id'] = $data['id'][$i];
                        $sdata['name'] = $data['name'][$i];
                        $res = M('goods_type')->save($sdata);
                    }
                } elseif (I('ctrl') == 'plan') {
                    for ($i = 0; $i < count($data['id']); $i++) {
                        $sdata['type_id'] = $data['id'][$i];
                        $sdata['type_name'] = $data['name'][$i];
                        $sdata['mode'] = $data['editmode'][$i];
                        $sdata['user_id'] = session('user_id');
                        $res = M('plan_type')->save($sdata);
                    }
                } else {
                    for ($i = 0; $i < count($data['id']); $i++) {
                        $sdata['code_id'] = $data['id'][$i];
                        $sdata['code_name'] = $data['name'][$i];
                        $sdata['parent_no'] = I('ctrl');
                        $res = M('sys_code')->save($sdata);
                    }
                }
            }
        }

        if ($res !== false) {
            $return = ['info' => '操作成功', 'status' => 1, 'icon' => 6, 'parent' => 1];
        } else {
            $return = ['info' => '操作失败', 'status' => 0, 'icon' => 6];
        }

        $this->ajaxReturn($return);
    }

    //删除类别
    public function delCate() {
        switch (I('ctrl')) {
            case 'goods':
                $res = M('goods_type')->delete(I('id'));
                break;
            case 'plan':
                $res = M('plan_type')->delete(I('id'));
                break;
            case 'flow':
                $res = M('flow_sort')->delete(I('id'));
                break;
            case 'form':
                $res = M('form_sort')->delete(I('id'));
                break;
            default:
                $res = M('sys_code')->delete(I('id'));
        }

        $this->ajaxReturn($res !== false ? ['info' => '删除成功', 'status' => 1, 'icon' => 6] : ['info' => '删除失败', 'status' => 0, 'icon' => 5]);
    }

}
